package com.newviews.tcmip.common.utils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: ExportExcelUtils
 * @Description:
 * @Author: lxc
 * @Date: 2024-03-10 15:49
 * @Version: 1.0
 **/
public class ExportExcelUtils {

    /**
     * 数据导出为csv表格
     * @param list
     * @param path
     * @throws IOException
     */
    public static void writeListOfMapsToCSV(List<Map<String, String>> list, String path) throws IOException {
        FileWriter writer = new FileWriter(path);

        // 写入标题行
//        String headers = String.join(",", list.get(0).keySet());
//        writer.write(headers + "\r\n");

        // 写入数据行
        for (Map<String, String> map : list) {
            for (String key : map.keySet()) {
                String str = map.get(key);
                if (StringUtils.isNotBlank(map.get(key))) {
                    str = map.get(key).replaceAll(",", "，");
                }
                str = String.join(",",key,str);

                writer.write(str + "\n");
            }

        }

        writer.flush();
        writer.close();
    }

    public static void writeListOfMapsToTxt(List<Map<String, String>> list, String path) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(path)) ;
            for (Map<String, String> map : list) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    writer.write(entry.getKey() + ": " + entry.getValue().toString());
                    writer.newLine();
                }
                writer.newLine(); // 在每个Map后添加一个空行
            }
        writer.flush();
        writer.close();
    }
}
